/**
 * 浏览器兼容性检测和错误处理工具
 */

// 检测浏览器版本
export function detectBrowser() {
  const userAgent = navigator.userAgent
  const browsers = {
    chrome: /Chrome\/(\d+)/.exec(userAgent),
    firefox: /Firefox\/(\d+)/.exec(userAgent),
    safari: /Safari\/(\d+)/.exec(userAgent),
    edge: /Edge\/(\d+)/.exec(userAgent)
  }
  
  for (const [name, match] of Object.entries(browsers)) {
    if (match) {
      return {
        name,
        version: parseInt(match[1])
      }
    }
  }
  
  return { name: 'unknown', version: 0 }
}

// 检查是否为老版本浏览器
export function isOldBrowser() {
  const browser = detectBrowser()
  const minVersions = {
    chrome: 110,
    firefox: 100,
    safari: 14,
    edge: 110
  }
  
  return browser.version < (minVersions[browser.name] || 999)
}

// 添加兼容性警告
export function showCompatibilityWarning() {
  if (isOldBrowser()) {
    const browser = detectBrowser()
    console.warn(`检测到老版本浏览器: ${browser.name} ${browser.version}，可能存在兼容性问题`)
    
    // 可选：显示用户友好的提示
    const warningDiv = document.createElement('div')
    warningDiv.style.cssText = `
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      background: #fff3cd;
      color: #856404;
      padding: 10px;
      text-align: center;
      z-index: 9999;
      border-bottom: 1px solid #ffeaa7;
      font-size: 14px;
      transition: opacity 0.3s ease-out;
    `
    warningDiv.innerHTML = `
      <span>检测到您使用的是较老版本的浏览器，建议升级到最新版本以获得最佳体验。</span>
      <button onclick="this.parentElement.remove()" style="margin-left: 10px; background: none; border: 1px solid #856404; color: #856404; padding: 2px 8px; cursor: pointer;">关闭</button>
    `
    document.body.appendChild(warningDiv)
    
    // 5秒后自动关闭提示
    setTimeout(() => {
      if (warningDiv && warningDiv.parentElement) {
        warningDiv.style.opacity = '0'
        setTimeout(() => {
          if (warningDiv.parentElement) {
            warningDiv.remove()
          }
        }, 300) // 等待淡出动画完成
      }
    }, 5000)
  }
}

// 错误处理和重试机制
export function handleCompatibilityError(error, retryCallback) {
  console.error('兼容性错误:', error)
  
  // 如果是老版本浏览器，尝试重新加载
  if (isOldBrowser() && retryCallback) {
    console.log('检测到老版本浏览器错误，尝试重新加载...')
    setTimeout(() => {
      try {
        retryCallback()
      } catch (retryError) {
        console.error('重试失败:', retryError)
        // 最后的备用方案：刷新页面
        if (confirm('页面加载出现问题，是否刷新页面？')) {
          window.location.reload()
        }
      }
    }, 1000)
  }
}

// 添加全局错误监听
export function setupGlobalErrorHandling() {
  // 监听未捕获的JavaScript错误
  window.addEventListener('error', (event) => {
    console.error('全局错误:', event.error)
    if (isOldBrowser()) {
      handleCompatibilityError(event.error)
    }
  })
  
  // 监听Promise rejection
  window.addEventListener('unhandledrejection', (event) => {
    console.error('未处理的Promise rejection:', event.reason)
    if (isOldBrowser()) {
      handleCompatibilityError(event.reason)
    }
  })
  
  // 监听资源加载错误
  window.addEventListener('error', (event) => {
    if (event.target !== window) {
      console.error('资源加载错误:', event.target.src || event.target.href)
      if (isOldBrowser()) {
        // 尝试重新加载失败的资源
        setTimeout(() => {
          if (event.target.tagName === 'SCRIPT') {
            const newScript = document.createElement('script')
            newScript.src = event.target.src
            document.head.appendChild(newScript)
          } else if (event.target.tagName === 'LINK') {
            const newLink = document.createElement('link')
            newLink.rel = 'stylesheet'
            newLink.href = event.target.href
            document.head.appendChild(newLink)
          }
        }, 2000)
      }
    }
  }, true)
}

// 检查关键功能是否可用
export function checkCriticalFeatures() {
  const features = {
    fetch: typeof fetch !== 'undefined',
    promise: typeof Promise !== 'undefined',
    arrow: (() => { try { eval('() => {}'); return true } catch { return false } })(),
    const: (() => { try { eval('const x = 1'); return true } catch { return false } })(),
    let: (() => { try { eval('let x = 1'); return true } catch { return false } })(),
    modules: 'noModule' in document.createElement('script')
  }
  
  const missing = Object.entries(features)
    .filter(([, supported]) => !supported)
    .map(([feature]) => feature)
  
  if (missing.length > 0) {
    console.warn('缺少关键功能:', missing)
    return false
  }
  
  return true
}